use Wx 0.15 qw[:allclasses];
use strict;
package wxColourTextList;

use Wx qw[:everything];
use base qw(Wx::Panel);
use strict;

#A panel to which coloured strings can be added, these are displayed flexibly on multiple rows.

sub new {
	my( $self, $parent, $id, $pos, $size, $style, $name ) = @_;
	    
	$parent = undef              unless defined $parent;
	$id     = -1                 unless defined $id;
	$pos    = wxDefaultPosition  unless defined $pos;
	$size   = wxDefaultSize      unless defined $size;
	$name   = ""                 unless defined $name;

	$style = wxDEFAULT_FRAME_STYLE 
		unless defined $style;

	#Create controls
	$self = $self->SUPER::new( $parent, $id, $pos, $size, $style, $name );

    #Register the sizing event
    Wx::Event::EVT_SIZE($self,  \&do_layout);

	#Do the layout
	$self->{sizer} = Wx::BoxSizer->new(wxVERTICAL);
	$self->SetSizer($self->{sizer});
	$self->{sizer}->Fit($self);
	$self->Layout();
	
#	$self->add_string('Hello');
#	$self->add_string('Hello2', wxBLUE);
#	$self->add_string('A very long and hopefully red string', wxRED);
#	$self->add_string('A very long and hopefully red string. A very long and hopeful', wxCYAN);
#	$self->add_string('self->add_string(A very long a', wxGREEN);
#	$self->add_string('Hello5');

	return $self;
}


sub clear {
	my $self = shift;
	#We send the destroy command
	foreach (@{$self->{legendstrings}}) { $_->Destroy(); }
	#We maintain a list of pointers to the destroyed objects...
	$self->{toDestroy} = $self->{legendstrings};
	delete $self->{legendstrings};
}

#Add a string, optional colour and font
sub add_string {
	my $self = shift;
	my $text = shift;
	my $colour = shift;
	my $font = shift;
	#If no text we return
	unless (defined $text) { return; }
	
	#Set default text font and colour
	unless (defined $colour) {$colour = wxBLACK; }
	unless (defined $font) {$font = wxNORMAL_FONT; }
	
	#Create the label
	my $label = Wx::StaticText->new($self, -1, $text, wxDefaultPosition, wxDefaultSize, wxALIGN_LEFT);
	
	#Set text attributes
	$label->SetForegroundColour($colour);
	$label->SetFont($font);
	$label->Wrap(-1);
	
	#Store the control
	push(@{$self->{legendstrings}}, $label);
	
	$self->do_layout();
}

#Redo the layout 
sub do_layout {
	my $self = shift;
	my ($w, $h) = $self->GetSizeWH();
	
	
	$self->{sizer}->Clear(0);
	
	my $cum_w = $w+1;
	my $sizer;
	my $dc = Wx::WindowDC->new($self);
	
	foreach (@{$self->{legendstrings}}) {
		my ($t_w, $t_h, $descent, $externalLeading ) = $dc->GetTextExtent($_->GetLabel,$_->GetFont); 
		if ($cum_w + $t_w > $w) {
			$cum_w = 0;
			$sizer = Wx::BoxSizer->new(wxHORIZONTAL);
			$self->{sizer}->Add($sizer,0,wxEXPAND|wxCENTER);		
		}  
		$sizer->Add($_,0,wxEXPAND|wxRIGHT,5);
		$sizer->SetItemMinSize($_,$t_w,$t_h);
		$cum_w += $t_w+5; 
	}
	$self->Layout();	
		
}

1;